#!/bin/bash

# This script help to
#  check the process of the service is running or not,
#  if the process is not running, it will restart the service, and write a message to error log.
#  if the process is running, it will do nothing.
#
#  Input: Service Name, Error Log File Path and Process Checking Mode

# Retrieve User Input
for i in "$@"
do
case $i in
    -s=*|--service=*)
        SERVICE="${i#*=}"
    ;;
    -l=*|--error_log=*)
        ERROR_LOG="${i#*=}"
    ;;
    -m=*|--mode=*)
        MODE="${i#*=}"
    ;;
    -h|--help)
        HELP=1
    ;;
    *)
        # unknown option
    ;;
esac
done

# Validate User Input
if [ "${SERVICE:-null}" = null ]; then
  echo "Error: Please define service name"
  HELP=1
fi

if [ "${ERROR_LOG:-null}" = null ]; then
  echo "Error: Please define error log file"
  HELP=1
fi

if [ "${MODE:-null}" = null ]; then
  MODE=1
fi

# Help Handling
if [ "${HELP:-null}" = 1 ]; then
    echo "---------------------------------------------------------------------------------"
    echo "Help - Input:"
    echo "-s | --service=<service name>, example -s=rabbitmq-server"
    echo "-l | --error-log=<error log file>, example -l=/var/log/batch/rabbitmq-error.log"
    echo "-m | --mode=<process checking mode>, example -m=1"
    echo "    Mode 1: Checking directly based on service running using 'pgrep xx'"
    echo "    Mode 2: Checking based on keyword match on process using 'ps ax | grep xx'"
    echo "---------------------------------------------------------------------------------"
    exit
fi

# Function: return 0 = Not OK, 1 = OK
check_service() {

    #Reference: http://stackoverflow.com/questions/2903354/bash-script-to-check-running-process
    if [ $MODE = 2 ]; then

        echo "Check service using ps ax ..."
        RESULT=$(ps ax | grep -v grep | grep -v $0 |grep $SERVICE)
    else

        echo "Check service using pgrep ..."
        RESULT=`pgrep ${SERVICE}`
    fi

    if [ "${RESULT:-null}" = null ]; then
        return 0
    else
        return 1
    fi
}

# On Error
if check_service ; then
    echo "Service not OK, service restarting ..."
    SERVICE_RESTART_CMD="/etc/init.d/$SERVICE restart"
    echo `$SERVICE_RESTART_CMD`

    sleep 5

    if check_service ; then

        MESSAGE="Service still not OK after restarted"
        SEVERITY="error"
    else

        MESSAGE="Service OK after restarted"
        SEVERITY="notice"
    fi

    NOW=$(date +"%Y-%m-%d %T")
    ERROR_MESSAGE="$NOW - $SEVERITY - service:$SERVICE host:$(hostname) message:$MESSAGE"

    echo $ERROR_MESSAGE >> $ERROR_LOG
    echo $ERROR_MESSAGE

else
    echo "Service OK"
fi

